package com.sxbbc.plat.controller.jz;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.service.config.Config;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.dto.Properties;
import com.sxbbc.common.basics.utils.encrypts.des.DESEncode;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.service.IAddressService;
import com.sxbbc.common.core.service.IWRolesService;
import com.sxbbc.common.core.service.IWUserService;
import com.sxbbc.common.core.service.IWWarehouseService;
import com.sxbbc.plat.common.WarehouseMapping;
import com.sxbbc.plat.util.SystemLog;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * 仓储管理 控制层
 *
 * @author leehao
 * @date 2019-07-01
 */
@Controller
public class WarehouseController {

    @Autowired
    private IWUserService iwUserService;
    @Autowired
    private IWWarehouseService iwWarehouseService;
    @Autowired
    private IWRolesService iwRolesService;
    @Autowired
    private IAddressService addressService;

    /* ------------------- 仓储管理员 ------------------- */

    /**
     * 仓库管理员页面
     *
     * @author leehao
     */
    @RequestMapping(value = WarehouseMapping.SHOW_WAREHOUSE_USER)
    public ModelAndView showWarehouseUserList() {
        List<WUser> list = iwUserService.list();
        for (WUser wUser : list) {
            wUser.setWarehouseName(iwWarehouseService.getById(wUser.getWid()).getName());
        }
        ModelAndView view = new ModelAndView(WarehouseMapping.SHOW_WAREHOUSE_USER);
        view.addObject("list", list);
        return view;
    }

    /**
     * 新增编辑仓库管理员 页面
     *
     * @author leehao
     */
    @RequestMapping(value = WarehouseMapping.SHOW_EDIT_WAREHOUSE_USER)
    public ModelAndView showEditWarehouseUser(Integer id) {
        //仓库管理员
        WUser wUser = iwUserService.getById(id);
        //仓库
        QueryWrapper<WWarehouse> wrapper = new QueryWrapper<>();
        wrapper.eq("status", StaticUtils.STATUS_YES);
        List<WWarehouse> warehouseList = iwWarehouseService.list();
        //角色
        ModelAndView view = new ModelAndView(WarehouseMapping.SHOW_EDIT_WAREHOUSE_USER);
        view.addObject("wUser", wUser);
        view.addObject("warehouseList", warehouseList);
        return view;
    }

    /**
     * 新增编辑仓库管理员
     */
    @RequestMapping(value = WarehouseMapping.EDIT_WAREHOUSE_USER)
    @ResponseBody
    @SystemLog(methods = "新增编辑仓库管理员", module = "仓储管理")
    public RestResponse editWarehouseUser(WUser wUser) {
        if (StringUtils.isBlank(wUser.getLogin())) {
            return GetRest.getFail("请输入登录名");
        }
        WUser user = iwUserService.selectByLogin(wUser.getLogin());
        if (wUser.getId() == null && user != null) {
            return GetRest.getFail("该用户名已存在");
        }
        if (StringUtils.isBlank(wUser.getName())) {
            return GetRest.getFail("请输入管理员名字");
        }
        if (StringUtils.isBlank(wUser.getPhone())) {
            return GetRest.getFail("请输入联系电话");
        }
        if (wUser.getWid() == null) {
            return GetRest.getFail("请选择仓库");
        }
        String encryptPassword = DESEncode.getInstance().encrypt(StaticUtils.DEFAULT_PASSWORD);
        wUser.setPassWord(encryptPassword);
        QueryWrapper<WRoles> wrapper = new QueryWrapper<>();
        wrapper.eq("target_id",0);
        WRoles wRoles = iwRolesService.getOne(wrapper);
        wUser.setRoleId(wRoles.getId()==null ? 1 : wRoles.getId());
        boolean save = iwUserService.saveOrUpdate(wUser);
        if (!save) {
            throw new ThrowJsonException("保存仓库管理员信息失败");
        }
        return GetRest.getSuccess("保存成功");
    }

    /**
     * 启用禁用仓库管理员
     *
     * @author leehao
     */
    @RequestMapping(value = WarehouseMapping.UPDATE_WUSER_STATUS)
    @ResponseBody
    public RestResponse updateWUserStatus(WUser wUser) {
        if (wUser.getId() == null) {
            return GetRest.getFail("请选择仓库管理员");
        }
        boolean update = iwUserService.updateById(wUser);
        if (!update) {
            throw new ThrowJsonException("更新仓库管理员信息失败");
        }
        return GetRest.getSuccess("更新成功");
    }

    /**
     * 删除仓库管理员
     *
     * @author leehao
     */
    @RequestMapping(value = WarehouseMapping.DELETE_WUSER)
    @ResponseBody
    public boolean deleteWUser(Integer id) {
        if (id == null) {
            return false;
        }
        boolean delete = iwUserService.removeById(id);
        if (!delete) {
            throw new ThrowJsonException("");
        }
        return delete;
    }

    /**
     * 角色页面
     *
     * @author leehao
     */
    @RequestMapping(value = WarehouseMapping.SHOW_WAREHOUSE_ROLE)
    public ModelAndView showWarehouseRole() {
        QueryWrapper<WRoles> wrapper = new QueryWrapper<>();
        wrapper.eq("target_id", 0);
        WRoles role = iwRolesService.getOne(wrapper);
        ModelAndView view = new ModelAndView(WarehouseMapping.SHOW_WAREHOUSE_ROLE);
        view.addObject("role", role);
        return view;
    }

    /**
     * 编辑角色
     *
     * @author leehao
     */
    @RequestMapping(value = WarehouseMapping.SHOW_EDIT_WAREHOUSE_ROLE)
    public ModelAndView showEditWarehouseRole(Integer id) {
        WRoles wRoles = iwRolesService.getById(id);
        List<WMenus> list = iwRolesService.queryMenusByRoleId(id);
        ModelAndView view = new ModelAndView(WarehouseMapping.SHOW_EDIT_WAREHOUSE_ROLE);
        view.addObject("role", wRoles);
        view.addObject("list", list);
        return view;
    }

    /**
     * 保存角色
     *
     * @author leehao
     */
    @RequestMapping(value = WarehouseMapping.EDIT_WAREHOUSE_ROLE)
    @ResponseBody
    public RestResponse saveWarehouseRole(WRoles role) {
        if (StringUtils.isBlank(role.getName())) {
            return GetRest.getFail("请填写角色名称");
        }
        if (StringUtils.isBlank(role.getMenuIds())) {
            return GetRest.getFail("请选择菜单");
        }
        //去重复
        Set<String> menuList = new HashSet<>(Arrays.asList(role.getMenuIds().split(",")));
        String menus = StringUtils.join(menuList.toArray(), ",");
        role.setMenuIds(menus);
        boolean b = iwRolesService.updateById(role);
        if (!b) {
            throw new ThrowJsonException("保存角色信息出错");
        }
        return GetRest.getSuccess("保存成功");
    }

    /* ------------------- 仓库管理 ------------------- */

    /**
     * 仓库列表
     *
     * @author leehao
     */
    @RequestMapping(value = WarehouseMapping.SHOW_WAREHOUSE_LIST)
    public ModelAndView showWarehouseList() {
        QueryWrapper<WWarehouse> wrapper = new QueryWrapper<>();
        wrapper.eq("status", StaticUtils.STATUS_YES);
        List<WWarehouse> list = iwWarehouseService.list(wrapper);
        ModelAndView view = new ModelAndView(WarehouseMapping.SHOW_WAREHOUSE_LIST);
        view.addObject("list", list);
        return view;
    }

    /**
     * 新增编辑仓库页面
     *
     * @param id 仓库信息ID
     * @author leehao
     */
    @RequestMapping(value = WarehouseMapping.SHOW_EDIT_WAREHOUSE)
    public ModelAndView showEditWarehouse(Integer id) {
        WWarehouse wWarehouse = iwWarehouseService.getById(id);
        //地址
        Address address = new Address();
        address.setPid(StaticUtils.ADDRESS_COUNTRY);
        //省份list
        List<Address> addressList = addressService.queryAddressByParentId(address);
        List<Address> cityList = new ArrayList<>();
        List<Address> areaList = new ArrayList<>();
        //城市list
        if (wWarehouse != null && wWarehouse.getProId() != null) {
            address.setPid(wWarehouse.getProId());
            cityList = addressService.queryAddressByParentId(address);
        }
        //区域list
        if (wWarehouse != null && wWarehouse.getCityId() != null) {
            address.setPid(wWarehouse.getCityId());
            areaList = addressService.queryAddressByParentId(address);
        }
        ModelAndView view = new ModelAndView(WarehouseMapping.SHOW_EDIT_WAREHOUSE);
        view.addObject("warehouse", wWarehouse);
        view.addObject("addressList", addressList);
        view.addObject("cityList", cityList);
        view.addObject("areaList", areaList);
        return view;
    }

    /**
     * 新增编辑仓库信息
     *
     * @param warehouse 仓库对象
     * @author leehao
     */
    @RequestMapping(value = WarehouseMapping.EDIT_WAREHOUSE)
    @ResponseBody
    @SystemLog(methods = "新增编辑仓库", module = "仓储管理")
    public RestResponse editWarehouse(WWarehouse warehouse) {
        if (StringUtils.isBlank(warehouse.getName())) {
            return GetRest.getFail("请输入仓库名称");
        }
        if (warehouse.getProId() == null) {
            return GetRest.getFail("请选择省份");
        }
        if (warehouse.getCityId() == null) {
            return GetRest.getFail("请选择城市");
        }
        if (warehouse.getAreaId() == null) {
            return GetRest.getFail("请选择地区");
        }
        if (StringUtils.isBlank(warehouse.getAddressDetail())) {
            return GetRest.getFail("请输入详细地址");
        }
        String nameExt = addressService.getAddrName(warehouse.getProId(), warehouse.getCityId(), warehouse.getAreaId());
        warehouse.setNameExt(nameExt);
        String address = nameExt + warehouse.getAddressDetail();
        //获取经纬度
        Properties properties = Config.properties;
        Map<String, String> map = CalcuUtils.getInstance().getLatAndLonByAmap(properties.getAmapKey(), address);
        if (!CollectionUtils.isEmpty(map)) {
            String lon = map.get("lon");
            String lat = map.get("lat");
            if (StringUtils.isNotBlank(lon) && StringUtils.isNotBlank(lat)) {
                warehouse.setLonVal(lon);
                warehouse.setLatVal(lat);
                warehouse.setStatus(StaticUtils.STATUS_YES);
            } else {
                warehouse.setStatus(StaticUtils.STATUS_NO);
            }
        }
        //保存仓库信息
        boolean save = iwWarehouseService.saveOrUpdate(warehouse);
        if (!save) {
            throw new ThrowJsonException("保存仓库信息失败");
        }
        return GetRest.getSuccess("保存成功");
    }
}
